'''
@author: saaj
@license: LGPL
'''


import cherrypy
import glob
import os.path
import io
import MySQLdb as mysql
from MySQLdb import cursors


class Model(object):
  
  _db = None
  
  
  def __init__(self):
    self._db = cherrypy.thread_data.db
    self._db.autocommit(True)
    
    try:
      self._db.ping(True) # it's conspiracy about reconnect flag
    except mysql.OperationalError:
      pass
    
    
class Note(Model):
  
  def count(self):
    cursor = self._db.cursor()
    cursor.execute("""
      SELECT COUNT(*)
      FROM note
    """)
    
    return cursor.fetchone()[0]
  
  def range(self, left, right):
    cursor = self._db.cursor(cursors.DictCursor)
    cursor.execute("""
      SELECT note_id `noteId`, name, comment 
      FROM note
      ORDER BY note_id ASC
      LIMIT %(offset)s, %(limit)s
    """, dict(offset = left, limit = right - left + 1))
    
    return cursor.fetchall()
  
  def create(self, name, comment = None):
    cursor = self._db.cursor()
    cursor.execute("""
      INSERT INTO note(name, comment)
      VALUES(%(name)s, %(comment)s)
    """, dict(name = name, comment = comment))
    
    return cursor.lastrowid
  
  def remove(self, id):
    self._db.cursor().execute("""
      DELETE FROM note
      WHERE note_id = %(noteId)s
    """, dict(noteId = id))
    
    
class File(Model):
  
  def _filename(self, name):
    return os.path.join(cherrypy.thread_data.path, "variable/storage", os.path.basename(name))
  
  def list(self):
    item = lambda name: dict(name = os.path.basename(name), size = os.path.getsize(name))
    return map(item, glob.glob(self._filename("*")))
    
  def get(self, name):
    return io.FileIO(self._filename(name), mode = 'r') 

  def put(self, name, file):
    with open(self._filename(name), "wb") as f:
      f.write(file.read())

  def remove(self, name):
    os.remove(self._filename(name))
